package com.ruoyi.asms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Lists;
import com.ruoyi.asms.domain.*;
import com.ruoyi.asms.domain.vo.*;
import com.ruoyi.asms.service.*;
import com.ruoyi.common.core.domain.AsmsAssetFullInfo;
import com.ruoyi.common.core.domain.KeyValueVo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.BusinessUtils;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.security.service.TokensService;
import com.ruoyi.system.controller.SysDeptController;
import com.ruoyi.system.controller.SysUserController;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 巡检任务信息Controller
 *
 * @author yfkj
 * @date 2021-10-21
 */
@RestController
@RequestMapping("/asms/InspectionTask")
public class InspectionTaskController extends BaseController {
    @Autowired
    private IInspectionTaskService inspectionTaskService;
    @Autowired
    private IInspectionService inspectionService;

    @Autowired
    private TokensService tokenService;
    @Autowired
    private IAsmsAssetFullInfoService asmsAssetFullInfoService;
    @Autowired
    private IAsmsFaultAssetService asmsFaultAssetService;
    @Autowired
    private IAsmsFaultResolveStageService asmsFaultResolveStageService;

//    @Autowired
//    private RemoteDeptService remoteDeptService;
//    @Autowired
//    private RemoteUserService remoteUserService;
    @Autowired
    private SysDeptController deptController;
    @Autowired
    private SysUserController userController;


    @GetMapping("/getInspectionTaskList")
    @ApiOperation("获取任务下拉列表")
    public AjaxResult getInspectionTaskList(InspectionTask inspectionTask){
        List<InspectionTaskBasicInfoVo> vos = new ArrayList<>();
        Set<Long> deptIds = tokenService.getLoginUser().getDeptIds();
        if (deptIds == null || deptIds.size() == 0) {
            return AjaxResult.success(vos);
        }
        R<Map<Long, SysDept>> deptListByIds = deptController.getDeptMapByIds(deptIds);
        if (R.FAIL == deptListByIds.getCode()) {
            throw new ServiceException(deptListByIds.getMsg());
        }
        QueryWrapper inspectionTaskQuery = getInspectionTaskQuery(inspectionTask);
        return AjaxResult.success(inspectionTaskService.list(inspectionTaskQuery));
    }

    @GetMapping("/getDeptByInspectionTaskId")
    @ApiOperation("根据巡检任务获取部门")
    public AjaxResult getDeptByInspectionTaskId(@RequestParam("inspectionTaskId") Long inspectionTaskId){

        InspectionTask inspectionTask = inspectionTaskService.getOne(new QueryWrapper<InspectionTask>().eq(InspectionTask.INSPECTION_TASK_ID, inspectionTaskId));
        String[] ids = inspectionTask.getAssetOwnIds().split(",");

        Set<Long> deptIds = new HashSet<>();

        for(int i =0;i<ids.length;i++){
            deptIds.add(Long.valueOf(ids[i]));
        }
        R<Map<Long, SysDept>> deptListByIds = deptController.getDeptMapByIds(deptIds);
        if (R.FAIL == deptListByIds.getCode()) {
            throw new ServiceException(deptListByIds.getMsg());
        }
        return AjaxResult.success(deptListByIds.getData().values());
    }


    @GetMapping("/getInspectionTaskBasicInfoList")
    @ApiOperation("获取巡检任务基础信息列表用于展示")
    public TableDataInfo getInspectionTaskBasicInfoList(InspectionTask inspectionTask) {

        //用户可看拥有的部门权限的巡检任务情况
        List<InspectionTaskBasicInfoVo> vos = new ArrayList<>();
        Set<Long> deptIds = tokenService.getLoginUser().getDeptIds();
        if (deptIds == null || deptIds.size() == 0) {
            return getDataTable(vos);
        }
        R<Map<Long, SysDept>> deptListByIds = deptController.getDeptMapByIds(deptIds);
        if (R.FAIL == deptListByIds.getCode()) {
            throw new ServiceException(deptListByIds.getMsg());
        }
        Map<Long, SysDept> deptMap = deptListByIds.getData();

        QueryWrapper queryWrapper = getInspectionTaskQuery(inspectionTask);
        startPage();
        List<InspectionTask> list = inspectionTaskService.list(queryWrapper);


        List<Long> userIds = new LinkedList<>();
        for (
                InspectionTask task : list) {
            InspectionTaskBasicInfoVo vo = new InspectionTaskBasicInfoVo();
            BeanUtils.copyProperties(task, vo);
            if (deptMap.containsKey(vo.getMaintenanceDeptId())) {
                vo.setMaintenanceDeptName(deptMap.get(vo.getMaintenanceDeptId()).getDeptFullName());
            }
            userIds.add(task.getChargeUserId());
            vos.add(vo);
        }

        Long[] longs = new Long[userIds.size()];
        userIds.toArray(longs);
        R<Map<Long, SysUser>> rUserList = userController.getUserListByIds(longs);
        if (rUserList == null || rUserList.getCode() == 500) {
            TableDataInfo t = new TableDataInfo();
            t.setMsg("用户服务调用失败");
            return t;
        }

        Map<Long, SysUser> userMap = rUserList.getData();
        if (userMap.isEmpty()) {
            return getDataTable(new ArrayList<>(0));
        }
        for (
                InspectionTaskBasicInfoVo vo : vos) {
            Long userId = vo.getChargeUserId();
            if (userMap.containsKey(userId)) {
                vo.setChargeUserName(userMap.get(userId).getUserName());
                vo.setPhonenumber(userMap.get(userId).getPhonenumber());
            }
        }
        return getDataTable(vos);

    }

    /**复用代码
     * @param inspectionTask
     * @return
     */
    public QueryWrapper getInspectionTaskQuery(InspectionTask inspectionTask){
        //获取巡检任务列表
        QueryWrapper<InspectionTask> queryWrapper = new QueryWrapper<InspectionTask>();
        if (StringUtils.isNotEmpty(inspectionTask.getInspectionTheme())) {
            queryWrapper.like(InspectionTask.INSPECTION_THEME, inspectionTask.getInspectionTheme());
        }
        queryWrapper.orderByDesc(InspectionTask.CREATE_TIME);
        if (SecurityUtils.getUserId() != 1L) {
            //用户能看的售后维护部门（通常为售后维护公司）
            Set<Long> userMaintenanceDeptIds = tokenService.getUserMaintenanceDeptIds();
            //用户能看的资产所有部门（通常为学校）
            Set<Long> userOwnDeptIds = tokenService.getUserOwnDeptIds();
            if (userMaintenanceDeptIds != null && userMaintenanceDeptIds.size() > 0) {
                queryWrapper.in(InspectionTask.MAINTENANCE_DEPT_ID, userMaintenanceDeptIds);
                if (userOwnDeptIds != null && userOwnDeptIds.size() > 0) {
                    ArrayList<Long> longs = Lists.newArrayList(userOwnDeptIds);
                    for (int i = 0; i < longs.size(); i++) {
                        queryWrapper.or().like(InspectionTask.ASSET_OWN_IDS, "," + longs.get(i) + ",").or()
                                .likeLeft(InspectionTask.ASSET_OWN_IDS, "," + longs.get(i)).or()
                                .likeRight(InspectionTask.ASSET_OWN_IDS, longs.get(i) + ",");
                    }
                }
            } else {
                if (userOwnDeptIds != null && userOwnDeptIds.size() > 0) {
                    ArrayList<Long> longs = Lists.newArrayList(userOwnDeptIds);
                    for (int i = 0; i < longs.size(); i++) {
                        if (i == 0) {
                            queryWrapper.like(InspectionTask.ASSET_OWN_IDS, "," + longs.get(i) + ",").or()
                                    .likeLeft(InspectionTask.ASSET_OWN_IDS, "," + longs.get(i)).or()
                                    .likeRight(InspectionTask.ASSET_OWN_IDS, longs.get(i) + ",");
                        } else {
                            queryWrapper.or().like(InspectionTask.ASSET_OWN_IDS, "," + longs.get(i) + ",").or()
                                    .likeLeft(InspectionTask.ASSET_OWN_IDS, "," + longs.get(i)).or()
                                    .likeRight(InspectionTask.ASSET_OWN_IDS, longs.get(i) + ",");
                        }
                    }

                }
            }
        }
        return queryWrapper;

    }
    @GetMapping("/getInspectionTaskFullInfoByItemId")
    @ApiOperation("根据任务Id获取任务基本信息用于展示或修改")
    public R<InspectionTask> getInspectionTaskFullInfoByItemId(@RequestParam("inspectionTaskId") Long inspectionTaskId) {
        return R.ok(inspectionTaskService.getById(inspectionTaskId));
    }

    @PostMapping("/addInspectionTask")
    @ApiOperation("新增巡检任务")
    public AjaxResult addInspectionTask(@RequestBody InspectionTaskAddVo vo) {
        if (vo == null || vo.getInspectionTheme() == null || vo.getStartTime() == null ||
                vo.getEndTime() == null || vo.getIsAutoCreate() == null || vo.getChargeUserId() == null) {
            return AjaxResult.error("任务信息错误");
        }
        String userName = SecurityUtils.getUsername();
        InspectionTask inspectionTask = new InspectionTask();
        BeanUtils.copyProperties(vo, inspectionTask);
        inspectionTask.setMaintenanceDeptId(SecurityUtils.getDeptId());
        inspectionTask.setCreateBy(userName);
        inspectionTask.setStatus(0);
        inspectionTask.setCreateTime(System.currentTimeMillis());

        if (inspectionTaskService.save(inspectionTask)) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("保存失败");
        }

    }

    @PostMapping("/editInspectionTask")
    @ApiOperation("修改巡检任务")
    public AjaxResult editInspectionTask(@RequestBody InspectionTaskEditVo vo) {
        if (vo == null || vo.getInspectionTaskId() == null) {
            return AjaxResult.error("任务信息错误");
        }

        String userName = SecurityUtils.getUsername();
        /** String userName =  "test";*/

        InspectionTask inspectionTask = new InspectionTask();
        BeanUtils.copyProperties(vo, inspectionTask);

        inspectionTask.setUpdateBy(userName);
        inspectionTask.setUpdateTime(System.currentTimeMillis());

        if (inspectionTaskService.update(inspectionTask, new UpdateWrapper<InspectionTask>().
                eq(InspectionTask.INSPECTION_TASK_ID, inspectionTask.getInspectionTaskId()))) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("修改失败");
        }
    }


    @GetMapping("/createInspectionsByTaskId")
    @ApiOperation("根据任务Id生成巡检记录")
    public R createInspectionByTaskId(@RequestParam("inspectionTaskId") Long inspectionTaskId) {
        if (inspectionTaskId == null) {
            return R.fail("任务信息错误");
        }
        InspectionTask task = inspectionTaskService.getById(inspectionTaskId);
        if (task.getStatus() > 1) {
            return R.fail("该任务已经生成过，请勿重复生成");
        }
//        if (!task.getIsAutoCreate().equals(1)) {
//            return R.fail("该任务只能自动生成，不能手动生成");
//        }
        //资产所属部门
        Long[] ownDeptIds = Convert.toLongArray(task.getAssetOwnIds());
        //资产位置id
        Long[] addressIds = Convert.toLongArray(task.getAddressIds());
        //资产类型id
        Long[] assetTypeIds = Convert.toLongArray(task.getAssetTypeIds());
        //安装绑定资产用户
        Long[] assetBindUserIds = Convert.toLongArray(task.getAssetBindUserIds());
        //资产批次
        Long[] projectIds = Convert.toLongArray(task.getProjectIds());

        List<AsmsAssetFullInfo> fullInfoList = asmsAssetFullInfoService.list(new QueryWrapper<AsmsAssetFullInfo>().
                eq(AsmsAssetFullInfo.MAINTENANCE_DEPT_ID, task.getMaintenanceDeptId()).
                in(ownDeptIds.length > 0, AsmsAssetFullInfo.OWN_DEPT_ID, ownDeptIds).
                in(addressIds.length > 0, AsmsAssetFullInfo.ADDRESS_ID, addressIds).
                in(assetTypeIds.length > 0, AsmsAssetFullInfo.ASSET_TYPE_ID, assetTypeIds).
                in(projectIds.length > 0, AsmsAssetFullInfo.PROJECT_ID, projectIds).
                in(assetBindUserIds.length > 0, AsmsAssetFullInfo.BIND_USER_ID, assetBindUserIds));
        Long[] inspectors = new Long[]{};
        ArrayList<Long> inspectorList = new ArrayList<>();
        if (StringUtils.isNotEmpty(task.getInspectionUserIds())) {
            inspectors = Convert.toLongArray(task.getInspectionUserIds());
            inspectorList = Lists.newArrayList(inspectors);
        }

        List<Inspection> inspections = new LinkedList<>();
        Map<String, Long> addressMap = new HashMap<>();
        Map<Long, Long> ownDeptMap = new HashMap<>();
        for (AsmsAssetFullInfo fullInfo : fullInfoList) {
            Inspection inspection = new Inspection();
            BeanUtils.copyProperties(fullInfo, inspection);
            inspection.setStartTime(task.getStartTime());
            inspection.setStatus(0);
            inspection.setInspectionTaskId(task.getInspectionTaskId());
            if (inspectors.length > 0) {
                //选择有巡检人员，则生成巡检任务时自动分配巡检人员
                //默认分配规则
                if (inspectors.length == 1) {
                    //规则一：若只有一个巡检人员，默认全部分给他
                    inspection.setInspectionUserId(inspectors[0]);
                } else {
                    if (ownDeptIds.length == 1) {
                        //规则二：若只有一个巡检客户，多个巡检人员，默认每个巡检人员负责一个区域
                        String addressAnc = fullInfo.getAddressAncestors();//0,12,15;0,12可表示一个顶级区域
                        String address = addressAnc.substring(0, addressAnc.indexOf(",", addressAnc.indexOf(",") + 1));
                        if (addressMap.containsKey(address)) {
                            //之前已为该区域分配用户
                            inspection.setInspectionUserId(addressMap.get(address));
                        } else {
                            //随机获取一个用户，并删除,如果可分配的用户集合没有用户可分，则重新再分一次，重置可分配的用户集合
                            if (inspectorList.size() == 0) {
                                inspectorList = Lists.newArrayList(inspectors);
                            }
                            Long userId = inspectorList.get((int) (Math.random() * inspectorList.size()));
                            addressMap.putIfAbsent(address, userId);
                            inspectorList.remove(userId);
                            inspection.setInspectionUserId(userId);
                        }
                    } else {
                        //规则三：若有多个巡检客户，多个巡检人员，默认每个巡检人员负责一个客户，
                        if (ownDeptMap.containsKey(fullInfo.getOwnDeptId())) {
                            //之前已为该区域分配用户
                            inspection.setInspectionUserId(ownDeptMap.get(fullInfo.getOwnDeptId()));
                        } else {
                            //随机获取一个用户，并删除,如果可分配的用户集合没有用户可分，则重新再分一次，重置可分配的用户集合
                            if (inspectorList.size() == 0) {
                                inspectorList = Lists.newArrayList(inspectors);
                            }
                            Long userId = inspectorList.get((int) (Math.random() * inspectorList.size()));
                            ownDeptMap.putIfAbsent(fullInfo.getOwnDeptId(), userId);
                            inspectorList.remove(userId);
                            inspection.setInspectionUserId(userId);
                        }
                    }

                }
            }
            inspections.add(inspection);
        }
        if (inspectionService.saveBatch(inspections)) {
            int status = 1;
            if (System.currentTimeMillis() > task.getStartTime()) {
                status = 2;
            }
            inspectionTaskService.update(new UpdateWrapper<InspectionTask>().
                    set(InspectionTask.STATUS, status).
                    eq(InspectionTask.INSPECTION_TASK_ID, task.getInspectionTaskId()));
            return R.ok();
        } else {
            return R.fail("未查询到相关巡检信息，任务生成失败");
        }


    }

    @GetMapping("/getStatisticByTaskId")
    @ApiOperation("根据任务Id查看巡检情况统计")
    public R<InspectionTaskStatisticVo> getStatisticByTaskId(@RequestParam("inspectionTaskId") Long inspectionTaskId) {
        if (inspectionTaskId == null) {
            return R.fail("任务id不能为空");
        }

        List<Inspection> inspections = inspectionService.list(new QueryWrapper<Inspection>().eq(Inspection.INSPECTION_TASK_ID, inspectionTaskId));

        HashMap<Long, InspectionTaskStatisticVo.DeptStatistic> deptStatisticMap = new HashMap<>(32);
        HashMap<Long, InspectionTaskStatisticVo.InspectorStatistic> inspectorStatisticMap = new HashMap<>(64);

        for (Inspection inspection : inspections) {
            Long ownDeptId = inspection.getOwnDeptId();
            InspectionTaskStatisticVo.DeptStatistic deptStatistic = null;
            if (ownDeptId == null) {
                continue;
            }
            if (!deptStatisticMap.containsKey(ownDeptId)) {
                deptStatistic = new InspectionTaskStatisticVo.DeptStatistic();
                deptStatistic.setDeptId(ownDeptId);
                R<SysDept> rDept =deptController.getDeptById(ownDeptId);
                if (rDept == null || rDept.getCode() == 500) {
                    return R.fail("获取部门id为" + inspection.getOwnDeptId() + "时，部门服务远程调用失败");
                }
                SysDept sysDept = rDept.getData();
                if (sysDept == null) {
                    return R.fail("找不到部门id为" + inspection.getOwnDeptId() + "的部门");
                }
                deptStatistic.setDeptName(sysDept.getDeptFullName());

                deptStatisticMap.put(ownDeptId, deptStatistic);
            }
            deptStatistic = deptStatisticMap.get(ownDeptId);
            if (inspection.getStatus() == 0) {
                deptStatistic.setNotFinishNumber(deptStatistic.getNotFinishNumber() + 1);
            } else if (inspection.getStatus() == 1) {
                deptStatistic.setFinishNumber(deptStatistic.getFinishNumber() + 1);
                switch (inspection.getResultType()) {
                    case 0:
                        deptStatistic.setRightNumber(deptStatistic.getRightNumber() + 1);
                        break;
                    case 1:
                        deptStatistic.setFinishNumber(deptStatistic.getFaultNumber() + 1);
                        break;
                    case 2:
                        deptStatistic.setLeakyBindNumber(deptStatistic.getLeakyBindNumber() + 1);
                        break;
                    case 3:
                        deptStatistic.setLoseCodeNumber(deptStatistic.getLoseCodeNumber() + 1);
                        break;
                    case 4:
                        deptStatistic.setOtherNumber(deptStatistic.getOtherNumber() + 1);
                }
            }



            Long userId = inspection.getInspectionUserId();
            InspectionTaskStatisticVo.InspectorStatistic inspectorStatistic = null;
            if (userId == null) {
                continue;
            }
            if (!inspectorStatisticMap.containsKey(userId)) {
                inspectorStatistic = new InspectionTaskStatisticVo.InspectorStatistic();
                inspectorStatistic.setUserId(userId);
                R<SysUser> rUser = userController.getUserByIdR(userId);
                if (rUser == null || rUser.getCode() == 500) {
                    return R.fail("获取用户id为" + userId + "时，用户服务远程调用失败");
                }
                SysUser sysUser = rUser.getData();
                if (sysUser == null) {
                    return R.fail("找不到用户id为" + userId + "的用户");
                }
                inspectorStatistic.setNickName(sysUser.getNickName());
                inspectorStatistic.setPhonenumber(sysUser.getPhonenumber());

                inspectorStatisticMap.put(userId, inspectorStatistic);
            }
            inspectorStatistic = inspectorStatisticMap.get(userId);
            if (inspection.getStatus() == 0) {
                inspectorStatistic.setNotFinishNumber(inspectorStatistic.getNotFinishNumber() + 1);
            } else if (inspection.getStatus() == 1) {
                inspectorStatistic.setFinishNumber(inspectorStatistic.getFinishNumber() + 1);
            }
        }
        List<InspectionTaskStatisticVo.DeptStatistic> deptStatisticList = new ArrayList<>(deptStatisticMap.values());
        List<InspectionTaskStatisticVo.InspectorStatistic> inspectorStatisticList = new ArrayList<>(inspectorStatisticMap.values());

        InspectionTaskStatisticVo vo = new InspectionTaskStatisticVo();
        vo.setDeptStatistics(deptStatisticList);
        vo.setInspectorStatistics(inspectorStatisticList);

        return R.ok(vo);

    }

    @ApiOperation("获取巡检任务下拉列表")
    @GetMapping("/getInspectionTaskSelect")
    public AjaxResult getInspectionTaskSelect() {
        QueryWrapper<InspectionTask> wrapper = new QueryWrapper<>();
        String deptType = tokenService.getLoginUser().getSysDept().getDeptType();
        if ((!SysUser.isAdmin(SecurityUtils.getUserId())) && deptType.contains("4")) {
            //巡检方查看本部门的巡检任务
            Long deptId = tokenService.getLoginUser().getDeptid();
            wrapper.eq(InspectionTask.MAINTENANCE_DEPT_ID, deptId);
        }
        List<InspectionTask> inspectionTaskList = inspectionTaskService.list(wrapper);
        ArrayList<KeyValueVo> keyValueVos = new ArrayList<>();
        for (InspectionTask inspectionTask : inspectionTaskList) {
            KeyValueVo vo = new KeyValueVo();
            vo.setKey(inspectionTask.getInspectionTaskId());
            vo.setValue(inspectionTask.getInspectionTheme());
            keyValueVos.add(vo);
        }
        return AjaxResult.success(keyValueVos);
    }

    @ApiOperation("获取巡检客户下拉框")
    @GetMapping("/getICustomerTreeSelect")
    public AjaxResult getICustomerTreeSelect(@ApiParam("选中的巡检任务的id")
                                             @RequestParam(value = "inspectionTaskId", required = false) Long inspectionTaskId) {
        ArrayList<KeyValueVo> vos = new ArrayList<>();
        InspectionTask inspectionTask = inspectionTaskService.getOne(new QueryWrapper<InspectionTask>()
                .eq(InspectionTask.INSPECTION_TASK_ID, inspectionTaskId), false);
        //从巡检客户id字符串中构造出巡检客户的id数组
        String assetOwnIds = inspectionTask.getAssetOwnIds();
        if (StringUtils.isEmpty(assetOwnIds)) {
            return AjaxResult.success(vos);
        }
        Long[] longArray = Convert.toLongArray(assetOwnIds);
        HashSet<Long> set = new HashSet<>(Arrays.asList(longArray));
        R<List<SysDept>> deptListByIds = deptController.getDeptListByIds(set);
        if (deptListByIds.getCode() == R.FAIL) {
            throw new ServiceException(deptListByIds.getMsg());
        }
        for (SysDept sysDept : deptListByIds.getData()) {
            KeyValueVo vo = new KeyValueVo();
            vo.setKey(sysDept.getDeptId());
            vo.setValue(sysDept.getDeptShortName());
            vos.add(vo);
        }
        return AjaxResult.success(vos);
    }

    @GetMapping("/getAllValidInspectionTasks")
    public R<List<InspectionTask>> getAllValidInspectionTasks() {
        List<InspectionTask> list = inspectionTaskService.list(new QueryWrapper<InspectionTask>()
                .eq(InspectionTask.STATUS, 0)//所有未开始的巡检任务
                .gt(InspectionTask.START_TIME, System.currentTimeMillis() - 10 * 24 * 60 * 60 * 1000)//提前10天的开始通知
                .orderByAsc(InspectionTask.START_TIME)//按开始时间升序
        );
        return R.ok(list);
    }


    @GetMapping(value="/downLoadInspections",produces = "application/octet-stream")
    public void sendInspectionStatic(HttpServletResponse response,@RequestParam("taskId") Long taskId) {
        InspectionTask inspectionTask = inspectionTaskService.getById(taskId);
        List<Inspection> inspections = inspectionService.list(new QueryWrapper<Inspection>().eq(Inspection.INSPECTION_TASK_ID, taskId));
        Set<Long> assetIds = new HashSet<>();
        Set<Long> faultIds = new HashSet<>();
        Set<Long> userIds = new HashSet<>();
        Set<Long> deptIds = new HashSet<>();
        deptIds.add(inspectionTask.getMaintenanceDeptId());
        for (Inspection inspection : inspections) {
            assetIds.add(inspection.getAssetId());
            if (inspection.getFaultId() != null && inspection.getFaultId() != 0) {
                faultIds.add(inspection.getFaultId());
            }
            userIds.add(inspection.getInspectionUserId());
            deptIds.add(inspection.getOwnDeptId());
        }
        List<AsmsAssetFullInfo> assetList = asmsAssetFullInfoService.list(new QueryWrapper<AsmsAssetFullInfo>().
                in(AsmsAssetFullInfo.ASSET_ID, assetIds));
        Map<Long, AsmsAssetFullInfo> assetIdFullInfoMap = new HashMap<>();
        assetList.forEach(asset -> assetIdFullInfoMap.put(asset.getAssetId(), asset));
        Map<Long, AsmsFaultAsset> faultIdFaultAssetMap = new HashMap<>();
        Map<Long, Long> faultAssetIdFaultIdMap = new HashMap<>();
        if (faultIds.size() > 0) {
            List<AsmsFaultAsset> faultList = asmsFaultAssetService.list(new QueryWrapper<AsmsFaultAsset>().
                    in(AsmsFaultAsset.FAULT_ID, faultIds));
            faultList.forEach(faultAsset -> {
                faultIdFaultAssetMap.put(faultAsset.getFaultId(), faultAsset);
                faultAssetIdFaultIdMap.put(faultAsset.getFaultAssetId(), faultAsset.getFaultId());
            });
        }
        R<Map<Long, SysUser>> rUsers = userController.getUserListByIds(userIds.toArray(new Long[0]));
        BusinessUtils.checkRemoteService(rUsers);
        Map<Long, AsmsFaultResolveStage> faultIdResolveStageMap = new HashMap<>();
        if (faultAssetIdFaultIdMap.size() > 0) {
            List<AsmsFaultResolveStage> asmsFaultResolveStages = asmsFaultResolveStageService.list(new QueryWrapper<AsmsFaultResolveStage>().
                    in(AsmsFaultReportStage.FAULT_ASSET_ID, faultAssetIdFaultIdMap.keySet()));
            if (asmsFaultResolveStages.size() > 0) {
                asmsFaultResolveStages.forEach(resolveStage -> faultIdResolveStageMap.put(faultAssetIdFaultIdMap.get(resolveStage.getFaultAssetId()), resolveStage));
            }
        }
        R<Map<Long, SysDept>> rDeptMap = deptController.
                getDeptNameAndManegerByDeptIds(new ArrayList<>(deptIds));
        BusinessUtils.checkRemoteService(rDeptMap);
        List<InspectionInfoVo> vos = new LinkedList<>();
        for (Inspection inspection : inspections) {
            InspectionInfoVo vo = new InspectionInfoVo();
            BeanUtils.copyProperties(inspection, vo);
            AsmsAssetFullInfo asmsAssetFullInfo = assetIdFullInfoMap.get(vo.getAddressId());
            vo.setInspectionTaskName(inspectionTask.getInspectionTheme());
            if (asmsAssetFullInfo != null) {
                vo.setAddressFullName(asmsAssetFullInfo.getAddressFullName());
                vo.setAssetTypeName(asmsAssetFullInfo.getAssetTypeName());
                vo.setAssetTypeId(asmsAssetFullInfo.getAssetTypeId());
            }
            AsmsFaultResolveStage asmsFaultResolveStage = faultIdResolveStageMap.get(inspection.getFaultId());
            if (asmsFaultResolveStage != null) {
                BeanUtils.copyProperties(asmsFaultResolveStage, vo);
            }
            Map<Long, SysDept> deptMap = rDeptMap.getData();
            if (deptMap.containsKey(inspection.getOwnDeptId())) {
                SysDept sysDept = deptMap.get(inspection.getOwnDeptId());
                vo.setOwnDeptName(sysDept.getDeptShortName());
                vo.setOwnDeptUserName(sysDept.getLeader());
                vo.setOwnDeptUserPhone(sysDept.getPhone());
            }
            Map<Long, SysUser> userMap = rUsers.getData();
            SysUser sysUser = userMap.get(vo.getInspectionUserId());
            if (sysUser != null) {
                vo.setInspectionUserName(sysUser.getNickName());
                vo.setInspectionUserPhone(sysUser.getPhonenumber());
            }
            //巡检结果类型(0：正常，1：设备故障，2：设备漏绑，3：安装位置码缺失，4：其他)
            if (inspection.getResultType() != null)
                switch (inspection.getResultType()) {
                    case 0:
                        vo.setResultTypeStr("正常");
                        break;
                    case 1:
                        vo.setResultTypeStr("设备故障");
                        break;
                    case 2:
                        vo.setResultTypeStr("设备漏绑");
                        break;
                    case 3:
                        vo.setResultTypeStr("安装位置码缺失");
                        break;
                    case 4:
                        vo.setResultTypeStr("其他");
                        break;
                }
            vo.setStatusStr(vo.getStatus() > 0 ? "处理结束" : "正在处理中");
            vo.setStartTimeStr(DateUtils.parseLongToStr(DateUtils.YYYY_MM_DD_HH_MM_SS_Z, vo.getStartTime()));
            vo.setEndTimeStr(DateUtils.parseLongToStr(DateUtils.YYYY_MM_DD_HH_MM_SS_Z, vo.getEndTime()));
            //(1硬件、2软件、3其他)
            if (vo.getFaultType() != null)
                switch (vo.getFaultType()) {
                    case 1:
                        vo.setFaultTypeStr("硬件");
                        break;
                    case 2:
                        vo.setFaultTypeStr("软件");
                        break;
                    case 3:
                        vo.setFaultTypeStr("其他");
                        break;
                }
            if (vo.getResolveType() != null)
                vo.setResolveTypeStr(vo.getResolveType() > 1 ? "远程解决" : "现场解决");
            vos.add(vo);
        }
        ExcelUtil<InspectionInfoVo> util = new ExcelUtil<InspectionInfoVo>(InspectionInfoVo.class);
        try {
            util.exportExcel(response, vos, "巡检报表");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
